package org.boot.chat.config;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.boot.chat.data.model.entity.ChatModelDO;
import org.boot.chat.data.model.service.ChatModelService;
import org.boot.chat.util.DynamicBeanRegistry;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 动态装配多个模型信息
 * @author 最爱芫荽
 * @email 15733440205@163.com
 */
@Slf4j
@Configuration
public class EasyChatModelsFactory {

    @Resource
    private ChatModelsProperties chatModelsProperties;

    @Resource
    private DynamicBeanRegistry dynamicBeanRegistry;
    
    @Resource
    private ChatModelService chatModelService;

    @PostConstruct
    public void initChatModels() {
        initBean();
    }

    public void initBean() {
        chatModelsProperties.setChatModels(chatModelService.list(new ChatModelDO(0)));
        if(chatModelsProperties.getChatModels().isEmpty()){
            //请检查数据库的模型数据是否为空
            log.warn("chat models is empty, please check database!");
            return;
        }
        for (ChatModelDO chatModel : chatModelsProperties.getChatModels()) {
            ChatModel model = OpenAiChatModel.builder()
                    .openAiApi(OpenAiApi.builder()
                            .apiKey(chatModel.getApiKey())
                            .baseUrl(chatModel.getBaseUrl())
                            .build())
                    .defaultOptions(OpenAiChatOptions.builder()
                            .model(chatModel.getModel())
                            .build())
                    .build();
            // 动态注册到Spring容器
            dynamicBeanRegistry.registerSingletonBean(chatModel.getBean(), model);
        }
        //初始化成功，模型数量
        log.info("init chat models is success! models count: {}", chatModelsProperties.getChatModels().size());
    }


}
